<template>
  <div class="player-page">
    <div class="player-header">
      <button class="back-btn" @click="back">
        <i class="fas fa-chevron-left"></i>
      </button>
      <h2 class="song-title">{{ song.name }}</h2>
      <button class="menu-btn" @click="openMenu">
        <i class="fas fa-ellipsis-v"></i>
      </button>
    </div>
    
    <div class="lyrics-section">
      <div class="lyrics-content" ref="lyricsContainer">
        <!-- 加载状态 -->
        <div v-if="lyricsLoading" class="lyrics-loading">
          <i class="fas fa-spinner fa-spin"></i>
          <span>歌词加载中...</span>
        </div>
        
        <!-- 歌词内容 -->
        <div 
          v-else-if="parsedLyrics.length > 0"
          v-for="(line, index) in parsedLyrics" 
          :key="index"
          :class="[
            'lyric-line',
            { 
              'active': index === currentLyricIndex,
              'passed': index < currentLyricIndex
            }
          ]"
          :ref="el => { if (index === currentLyricIndex) currentLyricRef = el }"
        >
          {{ line.text }}
        </div>
        
        <!-- 无歌词状态 -->
        <div v-else class="no-lyrics">
          <i class="fas fa-music"></i>
          <span>暂无歌词</span>
        </div>
      </div>
    </div>
    
    <div class="progress-section">
      <div 
        class="progress-bar" 
        ref="progressBar"
        @click="handleProgressClick"
        @mousedown="startDrag"
        @touchstart="startDrag"
      >
        <div class="progress" :style="{ width: progressPercent + '%' }"></div>
        <div 
          class="progress-thumb" 
          :style="{ left: progressPercent + '%' }"
          @mousedown="startDrag"
          @touchstart="startDrag"
        ></div>
      </div>
      <div class="time-display">
        <span>{{ formatTime(currentTime) }}</span>
        <span>{{ formatTime(duration) }}</span>
      </div>
    </div>
    
    <div class="player-controls">
      <button class="control-btn" @click="prevSong">
        <i class="fas fa-step-backward"></i>
      </button>
      <button class="play-pause-btn" @click="togglePlay">
        <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
      </button>
      <button class="control-btn" @click="nextSong">
        <i class="fas fa-step-forward"></i>
      </button>
    </div>
    
    <div class="play-mode">
      <!-- 添加模式提示文字 -->
      <div v-if="showModeTip" class="mode-tip">
        {{ modeText }}
      </div>
      <button class="mode-btn" @click="switchMode">
        <i :class="modeIcon"></i>
      </button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'

export default {
  name: 'PlayerPage',
  props: {
    song: Object,
    isPlaying: Boolean,
    currentTime: Number,
    duration: Number,
    playMode: String,
    lyrics: String
  },
  emits: ['toggle-play', 'prev-song', 'next-song', 'back', 'play-mode', 'set-current-time'],
  setup(props, { emit }) {
    const progressPercent = computed(() => {
      if (!props.duration) return 0
      return (props.currentTime / props.duration) * 100
    })
    
    const currentLyric = ref('')
    const showModeTip = ref(false) // 控制提示显示
    const modeText = ref('') // 提示文字内容
    const progressBar = ref(null)
    const isDragging = ref(false)
    const lyricsLoading = ref(false)
    
    // 歌词相关变量
    const parsedLyrics = ref([])
    const currentLyricIndex = ref(-1)
    const lyricsContainer = ref(null)
    const currentLyricRef = ref(null)

    const modeIcon = computed(() => {
      switch (props.playMode) {
        case 'sequential': return 'fas fa-list'
        case 'random': return 'fas fa-random'
        case 'single': return 'fas fa-redo'
        case 'list': return 'fas fa-retweet'
        case 'disabled': return 'fas fa-ban'
        default: return 'fas fa-list'
      }
    })
    
    // 获取模式对应的中文描述
    const getModeText = (mode) => {
      switch (mode) {
        case 'sequential': return '顺序播放'
        case 'random': return '随机播放'
        case 'single': return '单曲循环'
        case 'list': return '列表循环'
        case 'disabled': return '禁用切换'
        default: return '顺序播放'
      }
    }
    
    const togglePlay = () => {
      emit('toggle-play')
    }
    
    const prevSong = () => {
      emit('prev-song')
    }
    
    const nextSong = () => {
      emit('next-song')
    }
    
    const back = () => {
      emit('back')
    }
    
    const openMenu = () => {
      // 可以扩展更多菜单功能
      console.log('打开菜单')
    }
    
    // 处理进度条点击
    const handleProgressClick = (event) => {
      if (!props.duration || isDragging.value) return
      
      const progressBarRect = progressBar.value.getBoundingClientRect()
      const clickPosition = (event.clientX - progressBarRect.left) / progressBarRect.width
      const newTime = clickPosition * props.duration
      
      emit('set-current-time', newTime)
    }
    
    // 开始拖动
    const startDrag = (event) => {
      isDragging.value = true
      
      // 阻止默认行为，防止文本选择
      event.preventDefault()
      
      // 添加全局事件监听
      document.addEventListener('mousemove', handleDrag)
      document.addEventListener('mouseup', stopDrag)
      document.addEventListener('touchmove', handleDrag)
      document.addEventListener('touchend', stopDrag)
      
      // 初始拖动处理
      handleDrag(event)
    }
    
    // 处理拖动
    const handleDrag = (event) => {
      if (!isDragging.value || !props.duration) return
      
      const progressBarRect = progressBar.value.getBoundingClientRect()
      let clientX
      
      if (event.type.includes('touch')) {
        clientX = event.touches[0].clientX
      } else {
        clientX = event.clientX
      }
      
      // 计算点击位置在进度条上的比例
      let clickPosition = (clientX - progressBarRect.left) / progressBarRect.width
      clickPosition = Math.max(0, Math.min(1, clickPosition)) // 限制在0-1之间
      
      const newTime = clickPosition * props.duration
    }
    
    // 停止拖动
    const stopDrag = (event) => {
      if (!isDragging.value || !props.duration) return
      
      const progressBarRect = progressBar.value.getBoundingClientRect()
      let clientX
      
      if (event.type === 'touchend') {
        // 对于触摸结束，使用最后一次触摸位置
        clientX = event.changedTouches[0].clientX
      } else {
        clientX = event.clientX
      }
      
      // 计算最终位置
      let clickPosition = (clientX - progressBarRect.left) / progressBarRect.width
      clickPosition = Math.max(0, Math.min(1, clickPosition))
      
      const newTime = clickPosition * props.duration
      
      // 应用新的播放时间
      emit('set-current-time', newTime)
      
      // 清理事件监听
      document.removeEventListener('mousemove', handleDrag)
      document.removeEventListener('mouseup', stopDrag)
      document.removeEventListener('touchmove', handleDrag)
      document.removeEventListener('touchend', stopDrag)
      
      isDragging.value = false
    }
    
    const switchMode = () => {
      const modes = ['sequential', 'random', 'single', 'list', 'disabled']
      const currentIndex = modes.indexOf(props.playMode)
      const nextIndex = (currentIndex + 1) % modes.length
      const newMode = modes[nextIndex]
      
      // 显示提示文字
      modeText.value = getModeText(newMode)
      showModeTip.value = true
      
      // 2秒后隐藏提示
      setTimeout(() => {
        showModeTip.value = false
      }, 2000)
      
      emit('play-mode', newMode)
    }
    
    const formatTime = (time) => {
      if (isNaN(time)) return '0:00'
      
      const minutes = Math.floor(time / 60)
      const seconds = Math.floor(time % 60)
      return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
    }
    
    // 解析LRC歌词格式
    const parseLrc = (lrcText) => {
      if (!lrcText) return []
      
      const lines = lrcText.split('\n')
      const lyrics = []
      
      // 正则表达式匹配时间标签和歌词
      const timeTagRegex = /\[(\d+):(\d+\.\d+)\](.*)/
      
      lines.forEach(line => {
        const match = line.match(timeTagRegex)
        if (match) {
          const minutes = parseInt(match[1])
          const seconds = parseFloat(match[2])
          const text = match[3].trim()
          
          if (text) { // 只添加有歌词文本的行
            lyrics.push({
              time: minutes * 60 + seconds,
              text: text
            })
          }
        }
      })
      
      // 按时间排序
      lyrics.sort((a, b) => a.time - b.time)
      
      return lyrics
    }
    
    // 更新当前显示的歌词
    const updateCurrentLyric = () => {
      if (parsedLyrics.value.length === 0) return
      
      const currentTime = props.currentTime
      let newIndex = -1
      
      // 找到当前时间对应的歌词
      for (let i = parsedLyrics.value.length - 1; i >= 0; i--) {
        if (currentTime >= parsedLyrics.value[i].time) {
          newIndex = i
          break
        }
      }
      
      if (newIndex !== currentLyricIndex.value) {
        currentLyricIndex.value = newIndex
        scrollToCurrentLyric()
      }
    }
    
    // 滚动到当前歌词
    const scrollToCurrentLyric = async () => {
      await nextTick()
      
      if (currentLyricRef.value && lyricsContainer.value) {
        const container = lyricsContainer.value
        const activeLine = currentLyricRef.value
        
        // 计算滚动位置，使当前歌词在容器中间
        const containerHeight = container.clientHeight
        const lineHeight = activeLine.offsetHeight
        const scrollTop = activeLine.offsetTop - (containerHeight / 2) + (lineHeight / 2)
        
        // 平滑滚动
        container.scrollTo({
          top: scrollTop,
          behavior: 'smooth'
        })
      }
    }
    
    // 初始化歌词
    const initLyrics = () => {
      if (!props.lyrics) {
        parsedLyrics.value = []
        currentLyricIndex.value = -1
        return
      }
      
      parsedLyrics.value = parseLrc(props.lyrics)
      currentLyricIndex.value = -1
      
      // 重置滚动位置
      if (lyricsContainer.value) {
        lyricsContainer.value.scrollTop = 0
      }
    }
    
    // 组件卸载时清理事件监听
    onUnmounted(() => {
      document.removeEventListener('mousemove', handleDrag)
      document.removeEventListener('mouseup', stopDrag)
      document.removeEventListener('touchmove', handleDrag)
      document.removeEventListener('touchend', stopDrag)
    })
    
    // 监听歌词变化
    watch(() => props.lyrics, (newLyrics) => {
      initLyrics()
    })
    
    // 监听播放时间变化，更新歌词
    watch(() => props.currentTime, updateCurrentLyric)
    
    onMounted(() => {
      initLyrics()
    })
    
    return {
      progressPercent,
      parsedLyrics,
      currentLyricIndex,
      lyricsContainer,
      currentLyricRef,
      lyricsLoading,
      modeIcon,
      showModeTip,
      modeText,
      progressBar,
      isDragging,
      togglePlay,
      prevSong,
      nextSong,
      back,
      openMenu,
      handleProgressClick,
      startDrag,
      handleDrag,
      stopDrag,
      switchMode,
      formatTime
    }
  }
}
</script>

<style scoped>
.player-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #c62828, #d32f2f);
  color: white;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.player-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn, .menu-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.song-title {
  font-size: 18px;
  font-weight: 600;
  text-align: center;
  flex: 1;
  margin: 0 15px;
}

.lyrics-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40px 0;
}

.lyrics-content {
  text-align: center;
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  width: 100%;
  scroll-behavior: smooth;
}

/* 隐藏滚动条 */
.lyrics-content::-webkit-scrollbar {
  display: none;
}

.lyrics-content {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

/* 歌词加载状态 */
.lyrics-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  opacity: 0.7;
}

.lyrics-loading i {
  font-size: 24px;
}

.lyric-line {
  font-size: 18px;
  line-height: 2.5;
  margin-bottom: 8px;
  opacity: 0.6;
  transition: all 0.3s ease;
  padding: 8px 12px;
  border-radius: 8px;
}

.lyric-line.passed {
  opacity: 0.4;
  transform: scale(0.95);
}

.lyric-line.active {
  opacity: 1;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

.no-lyrics {
  opacity: 0.7;
  font-style: italic;
  font-size: 16px;
  line-height: 2;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.no-lyrics i {
  font-size: 24px;
}

.progress-section {
  margin-bottom: 30px;
}

.progress-bar {
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;
  user-select: none;
}

.progress {
  height: 100%;
  background: white;
  border-radius: 2px;
  transition: width 0.1s;
  position: relative;
}

/* 进度条拖动滑块 */
.progress-thumb {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 16px;
  height: 16px;
  background: white;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.2s;
}

.progress-bar:hover .progress-thumb {
  opacity: 1;
}

.progress-bar:active .progress-thumb {
  opacity: 1;
}

.time-display {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  opacity: 0.8;
}

.player-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  margin-bottom: 20px;
}

.control-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 18px;
}

.play-pause-btn {
  background: white;
  border: none;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  color: #c62828;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 24px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.play-mode {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  position: relative;
}

/* 模式提示样式 */
.mode-tip {
  position: absolute;
  top: -40px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  white-space: nowrap;
  animation: fadeInOut 1s ease-in-out;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translateY(10px);
  }
  20% {
    opacity: 1;
    transform: translateY(0);
  }
  80% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-10px);
  }
}

.mode-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  opacity: 0.8;
  padding: 10px;
}

.mode-btn:hover {
  opacity: 1;
}
</style>
